import React, { useEffect, useState } from 'react';
import { Button, message, Modal, Tree, TreeProps } from 'antd';
import { routes } from '../../../../config/routes';
import { cloneDeep } from 'lodash';
import { getCheckedKeysFun, setRoleMenuFun } from '@/services/ant-design-pro/systemApi';

function RoleMenuModal(prop) {
  const [treeData, setTreeData] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectData, setSelectData] = useState<any[]>([]);
  const [allCheck, setAllCheck] = useState(false);

  // 获取选中的数据
  function getSelectedData(routes, selected) {
    const selectedData = [];

    function traverse(routes) {
      routes.forEach((route) => {
        if (selected.includes(route.path)) {
          selectedData.push({ ...route, routes: [] });
          if (route.routes) {
            traverse(route.routes);
          }
        }
      });
    }

    traverse(routes);

    // 使用Map代替Object lookup，更快的查找性能
    const lookup = new Map(
      selectedData.map(({ path }) => [
        path,
        {
          ...selectedData.find((item) => item.path === path),
          routes: [],
        },
      ]),
    );

    // 直接从Map中删除routes属性，避免两次遍历
    selectedData.forEach((item) => delete item.routes);

    // 构建树形结构
    const tree = [];
    selectedData.forEach((item) => {
      if (item.parentPath === null) {
        tree.push(lookup.get(item.path));
      } else {
        lookup.get(item.parentPath).routes.push(lookup.get(item.path));
      }
    });

    setSelectData(tree);
  }

  const onCheck: TreeProps['onCheck'] = (checkedKeysValue, { halfCheckedKeys }) => {
    setCheckedKeys(checkedKeysValue);
    let margeKeys = [...new Set([...checkedKeysValue, ...halfCheckedKeys])];
    getSelectedData(cloneDeep(treeData), margeKeys);
  };

  // 递归排除数据中没有name的数据，同时添加parentKey
  const filterData = (data, parentPath = null) => {
    const result = [];
    data.forEach((item) => {
      if (item.routes) {
        item.routes = filterData(item.routes, item.path);
      }
      if (item.name) {
        item.parentPath = parentPath;
        result.push(item);
      }
    });
    return result;
  };

  // 获取角色菜单
  const getCheckedKeysByRoleId = () => {
    setCheckedKeys([]);
    getCheckedKeysFun(prop.currentRow.roleId).then((res) => {
      if (res.data.length > 0) {
        setCheckedKeys(JSON.parse(res.data));
      }
    });
  };

  useEffect(() => {
    if (prop.open) {
      let treeData = filterData(routes);
      setTreeData(treeData);
      getCheckedKeysByRoleId();
    }
  }, [prop.open]);

  // 全选按钮点击事件处理
  const handleSelectAll = () => {
    function getAllKeys(treeData, keys = []) {
      treeData.forEach((node) => {
        keys.push(node.path);
        if (node.routes) {
          getAllKeys(node.routes, keys);
        }
      });
      return keys;
    }

    if (allCheck) {
      setAllCheck(false);
      setCheckedKeys([]);
    } else {
      setAllCheck(true);
      // 设置所有节点为选中状态
      const allKeys = getAllKeys(treeData);
      getSelectedData(cloneDeep(treeData), allKeys);
      setCheckedKeys(allKeys);
    }
  };

  const onFinish = () => {
    setRoleMenuFun({
      roleId: prop.currentRow.roleId,
      routes: JSON.stringify(selectData),
      checkedKeys: JSON.stringify(checkedKeys),
    }).then(() => {
      message.success('设置成功');
      prop.onCancel(true);
    });
  };

  return (
    <>
      <Modal
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <Button type={'primary'} onClick={handleSelectAll}>
              {allCheck ? '全选' : '全不选'}
            </Button>
            <CancelBtn />
            <OkBtn />
          </>
        )}
        title="角色菜单"
        open={prop.open}
        onCancel={prop.onCancel}
        onOk={onFinish}
      >
        <Tree
          checkable
          onCheck={onCheck}
          treeData={treeData}
          checkedKeys={checkedKeys}
          fieldNames={{
            title: 'name',
            key: 'path',
            children: 'routes',
          }}
          expandedKeys={checkedKeys}
          autoExpandParent={true}
        />
      </Modal>
    </>
  );
}

export default RoleMenuModal;
